import json

from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

# from jwtproject.settings import SECRET_KEY
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as JiaMiClass


def generate_token(username):

    #  1. 实例化
    jiami_obj = JiaMiClass(secret_key=settings.SECRET_KEY)

    #  2. 加密--载荷 跟你业务相关
    data = {'name': username}

    # ==>  bytes.decode() == >ste
    secrect_str = jiami_obj.dumps(data).decode()

    return secrect_str

def verify_token(token):
    jiami_obj = JiaMiClass(secret_key=settings.SECRET_KEY)
    #  3. 解密
    try:
        jiami_obj.loads(token)
    except Exception as e:
        print(e)
        return False
    return True

class InfoView(View):
    def get(self, request):
        #  接收前端 传入的 token
        front_token = request.GET.get('token')

        # 判断token是否有效--有效代表登录过
        if not verify_token(front_token):
            return redirect('/login/')

        return render(request, 'info.html')

class LoginView(View):
    #  登录页面展示
    def get(self, request):

        return render(request, 'login.html')

    #  登录功能
    def post(self, request):
        data_dict = request.POST
        print('用户名:',data_dict.get('user'))
        print('密码:', data_dict.get('pwd'))

        #  生成 token
        jwt_token = generate_token(username=data_dict.get('user'))

        return render(request, 'index.html',context={'token': jwt_token})
